// pages/message/message.js
Page({
    data: {
        conversations: [],
        isLoading: true,
        userId: '',
        userInfo: null,
        messageWatch: null, // 消息监听对象
        refreshTimer: null // 定时刷新计时器
    },

    onLoad() {
        const userInfo = wx.getStorageSync('userInfo');
        if (!userInfo) {
            wx.navigateTo({
                url: '/pages/login/login'
            });
            return;
        }

        this.setData({
            userId: userInfo._id,
            userInfo
        });

        this.loadConversations();
        this.startRefreshTimer();
        this.listenForRealtimeMessages();
    },

    // 加载会话列表
    loadConversations() {
        this.setData({
            isLoading: true
        });

        wx.cloud.callFunction({
            name: 'getConversations',
            data: {
                userId: this.data.userId
                // userId: "0253ee36683566070042b1cc538e95f0"
            },
            success: (res) => {
                console.log(res);
                if (res.result.conversations.length) {
                    res.result.conversations.forEach(item => {
                        item.latestMessage.time = this.formatTime(item.latestMessage.createTime)
                        if(item.goodsInfo.goodsImage){
                            let arr = item.goodsInfo.goodsImage.split(',')
                            if(arr.length>0){
                                item.goodsImages = arr
                            }
                        }
                    })
                }
                this.setData({
                    conversations: res.result.conversations || [],
                    isLoading: false
                });
            },
            fail: (err) => {
                console.error('加载会话失败:', err);
                wx.showToast({
                    title: '加载失败',
                    icon: 'none'
                });
                this.setData({
                    isLoading: false
                });
            }
        });
    },

    // 监听实时消息
    listenForRealtimeMessages() {
        const db = wx.cloud.database();

        // 关闭已有监听
        if (this.messageWatch) {
            this.messageWatch.close();
        }

        // 监听所有发给当前用户的新消息
        this.messageWatch = db.collection('messages')
            .where({
                toUserId: this.data.userId,
                isRead: false
            })
            .watch({
                onChange: (snapshot) => {
                    console.log('收到新消息:', snapshot);
                    this.loadConversations();

                    // 显示新消息提示
                    if (snapshot.docChanges.length > 0) {
                        wx.showToast({
                            title: '有新消息',
                            icon: 'none'
                        });
                    }
                },
                onError: (err) => {
                    console.error('监听消息失败:', err);
                }
            });
    },

    // 定时刷新
    startRefreshTimer() {
        // 每30秒刷新一次
        this.data.refreshTimer = setInterval(() => {
            this.loadConversations();
        }, 30000);
    },

    // 进入聊天页面
    goToChat(e) {
        const { conversationId, otherUserId, goodsId } = e.currentTarget.dataset;
        wx.navigateTo({
          url: `/pages/chat/index?conversationId=${conversationId}&otherUserId=${otherUserId}&goodsId=${goodsId}`
        }); 
    },

    // 下拉刷新
    onPullDownRefresh() {
        this.loadConversations();
        wx.stopPullDownRefresh();
    },

    // 页面卸载时清理
    onUnload() {
        console.log('onUnload 执行，refreshTimer:', this.refreshTimer);
        // 清除定时器
        if (this.data.refreshTimer) {
            clearInterval(this.data.refreshTimer);
        }

        // 关闭消息监听
        if (this.messageWatch) {
            this.messageWatch.close();
        }
    },
    // 格式化时间戳为友好格式
    formatTime(timestamp) {
        if (!timestamp) return '未记录';

        const date = new Date(timestamp);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
});